iT邦幫忙

2025 iThome 鐵人賽

DAY 18
0
Software Development

clojure 30 days系列 第 18

clojure 30 days - day 16

  • 分享至 

  • xImage
  •  

Problem Description

My grandfather always predicted how old people would get, and right before he passed away he revealed his secret!

In honor of my grandfather's memory we will write a function using his formula!

Take a list of ages when each of your great-grandparent died.
Multiply each number by itself.
Add them all together.
Take the square root of the result.
Divide by two.
Example
predictAge(65, 60, 75, 55, 60, 63, 64, 45) === 86
Note: the result should be rounded down to the nearest integer.

Some random tests might fail due to a bug in the JavaScript implementation. Simply resubmit if that happens to you.

Note

這題根本是在考數學!
因為思路和步驟比較複雜,把筆記寫在 comment。
這題的的重點如下:

  • 陣列的操作(map, reduce)。
  • 數學運算(Math/sqrt, Math/floor)。
  • 輸入數字的個數不一定限制 8 個(雖然題目舉例是 8 位祖先),程式要能處理多個參數。

Implementation

; implement
(defn predicter [ages]
  (->> ages           ; Start a thread-last pipeline with ages.
       (map #(* % %)) ; Square each age.
       (reduce +)     ; Sum all squared values.
       Math/sqrt      ; Take the square root. | Java class method
       (#(/ % 2.0))   ; Divide by 2.0 (using an anonymous fn to keep % as the dividend in ->>).
       Math/floor     ; Floor the result | Java class method
       int))          ; Cast to integer and return. | Java class method called by Clojure


; test
; execute implement function
(defn tester [arg exp]
  (= (predicter arg) exp))

; args & exception
(comment
  (tester [65 60 75 55 60 63 64 45] 86)
  (tester [32 54 76 65 34 63 64 45] 79))

Tiny data flow (example input)

[65 60 75 55 60 63 64 45]
→ L3: (4225 3600 5625 3025 3600 3969 4096 2025)
→ L4: 30165
→ L5: 173.595...
→ L6: 86.797...
→ L7: 86.0
→ L8: 86


上一篇
clojure 30 days - day 15
系列文
clojure 30 days18
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言